package com.zwk.common.autoconfig;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.zwk.common.interceptor.GlobalMybatisInterceptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@ConditionalOnClass(name = "com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration")
public class CommonAutoConfiguration implements ApplicationContextAware {
    private ApplicationContext context;
    /**
     * myBatis自动填充
     * @return
     */
    @ConditionalOnMissingBean(MetaObjectHandler.class)
    @ConditionalOnProperty("common.global.mybatis-interceptor")
    @Bean
    public GlobalMybatisInterceptor globalMybatisInterceptor(){
        return new GlobalMybatisInterceptor();
    }

    /**
     * myBatis分页插件
     * @return
     */
    @ConditionalOnProperty("common.global.mybatis-plus-interceptor")
    @Bean("globalPlusInterceptor")
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        Map<String, MybatisPlusInterceptor> interceptorMap = context.getBeansOfType(MybatisPlusInterceptor.class);
        MybatisPlusInterceptor interceptor = interceptorMap.values().stream().reduce(new MybatisPlusInterceptor(), (res, item) -> {
            res.getInterceptors().addAll(item.getInterceptors());
            return res;
        });
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context=applicationContext;
    }
}
